<template>
    <t-dialog v-model:visible="visible" header="选择新闻" width="800"  @opened="loadRelations">
        <!-- 搜索 -->
        <div style="margin-bottom: 12px; display:flex; gap:8px;">
            <t-input
                    v-model="searchKeyword"
                    placeholder="输入新闻标题搜索"
                    clearable
                    @enter="onSearch"
            />
            <t-button theme="primary" @click="onSearch">搜索</t-button>
        </div>

        <!-- 新闻表格 -->
        <t-table
                :columns="columns"
                :data="newsPage.list"
                row-key="id"
                row-selectable
                v-model:selected-row-keys="currentPageSelectedIds"
                @select-change="handleSelectChange"
                bordered
                hover
        />

        <!-- 分页 -->
        <div class="pagination">
            <t-pagination
                    :total="newsPage.total"
                    :page-size="newsPage.pageSize"
                    :current="newsPage.pageNum"
                    @change="onPageChange"
            />
        </div>

        <!-- 已选新闻展示 -->
        <div v-if="allSelectedNews.length" class="selected-news-wrapper">
            <div class="selected-news-title">
                已选新闻（{{ allSelectedNews.length }} 条）：
            </div>
            <t-table
                    :columns="selectedColumns"
                    :data="allSelectedNews"
                    row-key="id"
                    size="small"
                    bordered
            />
        </div>

        <template #footer>
            <t-space>
                <t-button theme="default" @click="visible = false">取消</t-button>
                <t-button theme="primary" @click="confirmSelect">确定并保存</t-button>
            </t-space>
        </template>
    </t-dialog>
</template>

<script setup>
    import { reactive, ref, watch, onMounted, computed } from 'vue'
    import NewsService from '../../api/news'
    import { MessagePlugin } from 'tdesign-vue-next'
    import RelationService from "../../api/pageComponentDataRelation";

    const props = defineProps({
        modelValue: Boolean,
        pageId: Number,
        componentId: String
    })
    const emit = defineEmits(['update:modelValue', 'confirm'])

    const visible = ref(props.modelValue)
    watch(() => props.modelValue, v => (visible.value = v))
    watch(visible, v => emit('update:modelValue', v))

    // 搜索关键词
    const searchKeyword = ref('')

    // 分页数据
    const newsPage = reactive({ list: [], total: 0, pageNum: 1, pageSize: 10 })

    // 当前页已选 ID（表格 v-model）
    const currentPageSelectedIds = ref([])

    // 全局已选新闻对象数组
    const allSelectedNews = ref([])

    // 表格列
    const columns = [
        { colKey: 'row-select', type: 'multiple', width: 50 },
        { colKey: 'id', title: 'ID', width: 60 },
        { colKey: 'title', title: '标题', width: 200 },
        { colKey: 'type', title: '类型', width: 100 },
        { colKey: 'description', title: '描述', ellipsis: true }
    ]

    const selectedColumns = [
        { colKey: 'id', title: 'ID', width: 60 },
        { colKey: 'title', title: '标题', width: 200 },
        { colKey: 'type', title: '类型', width: 100 }
    ]

    // ---------------------- 数据加载 ----------------------
    const fetchNews = async () => {
        try {
            const data = {
                pageNum: newsPage.pageNum,
                pageSize: newsPage.pageSize,
                keyword: searchKeyword.value
            };
            const res = await NewsService.getNewsPage(data)
            newsPage.list = res.data.records
            newsPage.total = res.data.total
        } catch (e) {
            console.error(e)
            MessagePlugin.error('获取新闻列表失败')
        }
    }

    const onPageChange = (page) => {
        newsPage.pageNum = page.current
        fetchNews()
    }

    // ---------------------- 搜索 ----------------------
    const onSearch = () => {
        newsPage.pageNum = 1
        fetchNews()
    }

    // ---------------------- 多页多选逻辑 ----------------------
    const handleSelectChange = (selectedKeys, { selectedRowData }) => {
        // 移除当前页取消的
        allSelectedNews.value = allSelectedNews.value.filter(
            n => !newsPage.list.map(x => x.id).includes(n.id)
        )
        // 添加当前页选中的
        allSelectedNews.value.push(...selectedRowData)
    }

    // ---------------------- 确认选择 ----------------------
    const confirmSelect = async () => {
        if (!allSelectedNews.value.length) {
            MessagePlugin.warning('请至少选择一条新闻')
            return
        }

        const relations = []
        allSelectedNews.value.forEach(news => {
            relations.push({
                pageId: props.pageId,
                componentId: props.componentId,
                componentType: 'news',
                bizId: news.id,
                parentId: null,
                sortOrder: 0,
                status: 1
            })
        })

        try {
            await RelationService.saveRelations(props.pageId, props.componentId, relations)
            MessagePlugin.success('保存成功')
            emit('confirm', allSelectedNews.value)
            visible.value = false
        } catch (e) {
            console.error(e)
            MessagePlugin.error('保存失败')
        }
    }

    const loadRelations = async () => {
        if (!props.pageId || !props.componentId) return
        try {
            const res = await RelationService.getByComponentId(props.componentId)
            const list = res.data || []
            if (list.length === 0) return
            const relatedNews = list || []
            // 如果当前页有新闻数据，更新选中状态
            if (newsPage.list.length > 0) {
                currentPageSelectedIds.value = newsPage.list
                    .filter(n => relatedNews.some(r => r.bizId === n.id))
                    .map(n => n.id)
            }
            MessagePlugin.success('已加载组件关联数据')
        } catch (e) {
            console.error(e)
            MessagePlugin.error('加载关联数据失败')
        }
    }

    onMounted(fetchNews)
</script>

<style scoped>
    .pagination {
        margin-top: 10px;
        display: flex;
        justify-content: center;
    }

    .selected-news-wrapper {
        margin-top: 16px;
        background-color: #fafafa;
        border: 1px solid #eee;
        padding: 12px;
        border-radius: 8px;
    }

    .selected-news-title {
        font-weight: 500;
        margin-bottom: 8px;
    }
</style>
